// pages/todo/todo.js
Page({
  // 自定义日期格式化函数，确保中文显示
  formatDate: function(date) {
    const d = new Date(date);
    if (isNaN(d.getTime())) return '';
    
    const year = d.getFullYear();
    const month = d.getMonth() + 1;
    const day = d.getDate();
    const hour = d.getHours();
    const minute = d.getMinutes();
    const second = d.getSeconds();
    
    const hour12 = hour % 12 || 12;
    const ampm = hour < 12 ? '上午' : '下午';
    
    return `${year}年${month}月${day}日${ampm}${hour12}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
  },
  data: {
    inputValue: '',
    todoList: [],
    completedList: [],
    currentTab: 0, // 0: 待办事项, 1: 时间线, 2: 已完成
    weeklyTodos: [], // 按周分组的待办事项
    todoWeeklyTodos: [], // 按周分组的待办事项（仅待办）
    showAddWeeklyModal: false, // 添加时间线待办弹窗显示状态
    showAddDateModal: false, // 添加指定日期待办弹窗显示状态
    weeklyInputValue: '', // 时间线待办输入内容
    currentWeekId: '', // 当前选择的周ID
    selectedDate: '', // 选择的日期
    selectedDateWeekId: '' // 选择日期对应的周ID
  },

  onLoad: function () {
    this.loadTodoData()
  },

  onShow: function () {
    // 每次显示页面时重新加载数据
    this.loadTodoData()
  },

  // 从本地存储加载待办数据
  loadTodoData: function() {
    const todoList = wx.getStorageSync('todoList') || []
    const completedList = wx.getStorageSync('completedList') || []
    
    // 将待办事项按周分组
    const weeklyTodos = this.groupTodosByWeek([...todoList, ...completedList])
    // 将待办事项Tab中的事项按周分组
    const todoWeeklyTodos = this.groupTodosByWeek(todoList)
    
    this.setData({
      todoList: todoList,
      completedList: completedList,
      weeklyTodos: weeklyTodos,
      todoWeeklyTodos: todoWeeklyTodos
    })
  },

  // 按周分组待办事项
  groupTodosByWeek: function(todos) {
    const weeklyMap = new Map()
    const now = new Date()
    const currentWeekId = this.getWeekId(now)
    
    todos.forEach(todo => {
      // 优先使用ISO格式的日期字符串进行解析，确保能正确获取日期信息
      let createDate
      if (todo.createTimeIso) {
        createDate = new Date(todo.createTimeIso)
      } else {
        createDate = new Date(todo.createTime)
      }
      
      // 确保日期对象有效
      if (isNaN(createDate.getTime())) {
        createDate = new Date()
      }
      
      const weekId = this.getWeekId(createDate)
      
      if (!weeklyMap.has(weekId)) {
        weeklyMap.set(weekId, {
          weekId: weekId,
          weekLabel: this.getWeekLabel(weekId),
          todos: [],
          expanded: weekId === currentWeekId // 默认展开当前周
        })
      }
      
      weeklyMap.get(weekId).todos.push(todo)
    })
    
    // 转换为数组并按周ID排序（最新的周在前）
    const weeklyTodos = Array.from(weeklyMap.values())
    weeklyTodos.sort((a, b) => b.weekId.localeCompare(a.weekId))
    
    return weeklyTodos
  },

  // 获取周ID
  getWeekId: function(date) {
    if (!date || isNaN(date.getTime())) {
      date = new Date()
    }
    
    const year = date.getFullYear()
    const workingDate = new Date(date)
    
    // 确定一年中的第一周
    const firstDayOfYear = new Date(year, 0, 1)
    const dayOfWeek = firstDayOfYear.getDay() || 7 // 0 表示星期日，转换为 7
    const daysToFirstMonday = (8 - dayOfWeek) % 7
    
    const firstMonday = new Date(year, 0, 1 + daysToFirstMonday)
    
    // 计算当前日期与第一周星期一的天数差
    const timeDiff = workingDate - firstMonday
    const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
    
    // 计算周数（向上取整）
    let weekNum = Math.floor(daysDiff / 7) + 1
    
    // 如果日期在第一周星期一之前，那么属于上一年的最后一周
    if (workingDate < firstMonday) {
      const prevYear = year - 1
      const prevYearFirstMonday = new Date(prevYear, 0, 1)
      const prevDayOfWeek = prevYearFirstMonday.getDay() || 7
      const prevDaysToFirstMonday = (8 - prevDayOfWeek) % 7
      const prevFirstMonday = new Date(prevYear, 0, 1 + prevDaysToFirstMonday)
      
      // 计算上一年的总周数
      const nextYearFirstMonday = new Date(year, 0, 1)
      const nextDayOfWeek = nextYearFirstMonday.getDay() || 7
      const nextDaysToFirstMonday = (8 - nextDayOfWeek) % 7
      const nextFirstMonday = new Date(year, 0, 1 + nextDaysToFirstMonday)
      
      const prevYearTimeDiff = nextFirstMonday - prevFirstMonday
      const prevYearWeeks = Math.floor(prevYearTimeDiff / (1000 * 60 * 60 * 24 * 7))
      
      return `${prevYear}W${String(prevYearWeeks).padStart(2, '0')}`
    }
    
    // 如果是12月31日，但属于下一年的第一周
    if (workingDate.getMonth() === 11 && workingDate.getDate() >= 29) {
      const nextYearFirstMonday = new Date(year + 1, 0, 1)
      const nextDayOfWeek = nextYearFirstMonday.getDay() || 7
      const nextDaysToFirstMonday = (8 - nextDayOfWeek) % 7
      const nextFirstMonday = new Date(year + 1, 0, 1 + nextDaysToFirstMonday)
      
      if (workingDate >= nextFirstMonday) {
        return `${year + 1}W01`
      }
    }
    
    return `${year}W${String(weekNum).padStart(2, '0')}`
  },

  // 获取周标签
  getWeekLabel: function(weekId) {
    try {
      // 解析周ID，获取年份和周数
      const parts = weekId.split('W')
      if (parts.length !== 2) {
        return '本周'
      }
      
      const year = parseInt(parts[0], 10)
      let weekNum = 1
      
      if (parts.length > 1 && parts[1]) {
        const parsedNum = parseInt(parts[1], 10)
        // 确保解析结果是有效的数字且在合理范围内
        if (!isNaN(parsedNum) && parsedNum > 0 && parsedNum <= 53) {
          weekNum = parsedNum
        }
      }
      
      const workingDate = new Date(year, 0, 1)
      
      // 确定一年中的第一周
      const firstDayOfYear = new Date(year, 0, 1)
      const dayOfWeek = firstDayOfYear.getDay() || 7 // 0 表示星期日，转换为 7
      const daysToFirstMonday = (8 - dayOfWeek) % 7
      
      const firstMonday = new Date(year, 0, 1 + daysToFirstMonday)
      
      // 计算当前周的星期一日期
      const currentWeekMonday = new Date(firstMonday)
      currentWeekMonday.setDate(firstMonday.getDate() + (weekNum - 1) * 7)
      
      const startOfWeek = new Date(currentWeekMonday)
      const endOfWeek = new Date(startOfWeek);
      endOfWeek.setDate(endOfWeek.getDate() + 6); // 周日
      
      const formatDate = (d) => {
        return `${d.getMonth() + 1}月${d.getDate()}日`
      }
      
      return `${formatDate(startOfWeek)} - ${formatDate(endOfWeek)}`
    } catch (error) {
      console.error('获取周标签失败:', error)
      return '本周'
    }
  },

  // 切换Tab
  switchTab: function(e) {
    const currentTab = parseInt(e.currentTarget.dataset.index)
    this.setData({
      currentTab: currentTab
    })
  },

  // 获取时间线待办事项总数
  getWeeklyTodosCount: function() {
    return this.data.weeklyTodos.reduce((count, week) => count + week.todos.length, 0)
  },

  // 切换周待办列表的展开/收起状态
  toggleWeekTodos: function(e) {
    const weekId = e.currentTarget.dataset.weekid
    const currentTab = this.data.currentTab
    
    if (currentTab === 0) {
      // 待办事项Tab
      const todoWeeklyTodos = this.data.todoWeeklyTodos.map(week => {
        if (week.weekId === weekId) {
          return { ...week, expanded: !week.expanded }
        }
        return week
      })
      
      this.setData({
        todoWeeklyTodos: todoWeeklyTodos
      })
    } else if (currentTab === 1) {
      // 时间线Tab
      const weeklyTodos = this.data.weeklyTodos.map(week => {
        if (week.weekId === weekId) {
          return { ...week, expanded: !week.expanded }
        }
        return week
      })
      
      this.setData({
        weeklyTodos: weeklyTodos
      })
    }
  },

  // 日期选择变化
  onDateChange: function(e) {
    const selectedDate = e.detail.value
    const date = new Date(selectedDate)
    const weekId = this.getWeekId(date)
    
    this.setData({
      selectedDate: selectedDate,
      selectedDateWeekId: weekId
    })
  },
  
  // 显示添加指定日期待办的弹窗
  showAddDateModal: function() {
    this.setData({
      showAddDateModal: true,
      weeklyInputValue: ''
    })
  },
  
  // 关闭添加指定日期待办的弹窗
  closeAddDateModal: function() {
    this.setData({
      showAddDateModal: false,
      weeklyInputValue: ''
    })
  },
  
  // 打开添加每周待办的弹窗
  addWeeklyTodo: function(e) {
    const weekId = e.currentTarget.dataset.weekid
    this.setData({
      showAddWeeklyModal: true,
      weeklyInputValue: '',
      currentWeekId: weekId
    })
  },

  // 处理每周待办输入框的输入
  onWeeklyInput: function(e) {
    this.setData({
      weeklyInputValue: e.detail.value
    })
  },

  // 取消添加每周待办
  cancelAddWeeklyTodo: function() {
    this.setData({
      showAddWeeklyModal: false,
      weeklyInputValue: '',
      currentWeekId: ''
    })
  },

  // 确认添加每周待办
  confirmAddWeeklyTodo: function() {
    if (!this.data.weeklyInputValue.trim()) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none'
      })
      return
    }

    // 检查是否有选择的日期，如果有则使用选择的日期，否则使用当前时间
    // 使用ISO格式存储日期，确保后续解析时能正确获取日期信息
    const dateObj = this.data.selectedDate ? 
      new Date(this.data.selectedDate) : 
      new Date();
    
    // 保存ISO格式的日期字符串用于解析
    const createTimeIso = dateObj.toISOString();
    // 使用自定义日期格式化函数，确保中文显示
    const createTimeDisplay = this.formatDate(dateObj);

    const newTodo = {
      id: Date.now(),
      content: this.data.weeklyInputValue.trim(),
      createTime: createTimeDisplay,
      createTimeIso: createTimeIso
    }

    const todoList = [newTodo, ...this.data.todoList]
    
    // 更新时间线数据
    const weeklyTodos = this.groupTodosByWeek([...todoList, ...this.data.completedList])
    const todoWeeklyTodos = this.groupTodosByWeek(todoList)
    
    this.setData({
      todoList: todoList,
      weeklyTodos: weeklyTodos,
      todoWeeklyTodos: todoWeeklyTodos,
      showAddWeeklyModal: false,
      showAddDateModal: false,
      weeklyInputValue: ''
    })

    // 保存到本地存储
    wx.setStorageSync('todoList', todoList)

    wx.showToast({
      title: '添加成功',
      icon: 'success',
      duration: 1000
    })
  },

  // 输入框内容变化
  onInput: function(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  // 添加待办事项
  addTodo: function() {
    if (!this.data.inputValue.trim()) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none'
      })
      return
    }

    const dateObj = new Date();
    
    // 保存ISO格式的日期字符串用于解析
    const createTimeIso = dateObj.toISOString();
    // 使用自定义日期格式化函数，确保中文显示
    const createTimeDisplay = this.formatDate(dateObj);

    const newTodo = {
      id: Date.now(),
      content: this.data.inputValue.trim(),
      createTime: createTimeDisplay,
      createTimeIso: createTimeIso
    }

    const todoList = [newTodo, ...this.data.todoList]
    
    // 更新时间线数据
    const weeklyTodos = this.groupTodosByWeek([...todoList, ...this.data.completedList])
    const todoWeeklyTodos = this.groupTodosByWeek(todoList)
    
    this.setData({
      todoList: todoList,
      weeklyTodos: weeklyTodos,
      todoWeeklyTodos: todoWeeklyTodos,
      inputValue: ''
    })

    // 保存到本地存储
    wx.setStorageSync('todoList', todoList)

    wx.showToast({
      title: '添加成功',
      icon: 'success',
      duration: 1000
    })
  },

  // 完成待办事项
  completeTodo: function(e) {
    const id = e.currentTarget.dataset.id
    const todoList = this.data.todoList.filter(todo => todo.id !== id)
    const completedTodo = this.data.todoList.find(todo => todo.id === id)
    
    if (completedTodo) {
      const completedItem = {
        ...completedTodo,
        completeTime: this.formatDate(new Date())
      }
      const completedList = [completedItem, ...this.data.completedList]
      
      // 更新时间线数据
      const weeklyTodos = this.groupTodosByWeek([...todoList, ...completedList])
      const todoWeeklyTodos = this.groupTodosByWeek(todoList)
      
      this.setData({
        todoList: todoList,
        completedList: completedList,
        weeklyTodos: weeklyTodos,
        todoWeeklyTodos: todoWeeklyTodos
      })
      
      // 保存到本地存储
      wx.setStorageSync('todoList', todoList)
      wx.setStorageSync('completedList', completedList)
      
      wx.showToast({
        title: '已完成',
        icon: 'success',
        duration: 1000
      })
    }
  },

  // 恢复待办事项
  restoreTodo: function(e) {
    const id = e.currentTarget.dataset.id
    const completedList = this.data.completedList.filter(todo => todo.id !== id)
    const restoredTodo = this.data.completedList.find(todo => todo.id === id)
    
    if (restoredTodo) {
      const todoItem = {
        ...restoredTodo
      }
      delete todoItem.completeTime
      const todoList = [todoItem, ...this.data.todoList]
      
      // 更新时间线数据
      const weeklyTodos = this.groupTodosByWeek([...todoList, ...completedList])
      const todoWeeklyTodos = this.groupTodosByWeek(todoList)
      
      this.setData({
        todoList: todoList,
        completedList: completedList,
        weeklyTodos: weeklyTodos,
        todoWeeklyTodos: todoWeeklyTodos
      })
      
      // 保存到本地存储
      wx.setStorageSync('todoList', todoList)
      wx.setStorageSync('completedList', completedList)
      
      wx.showToast({
        title: '已恢复',
        icon: 'success',
        duration: 1000
      })
    }
  },

  // 删除待办事项
  deleteTodo: function(e) {
    const id = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个待办事项吗？',
      success: res => {
        if (res.confirm) {
          const todoList = this.data.todoList.filter(todo => todo.id !== id)
          
          // 更新时间线数据
          const weeklyTodos = this.groupTodosByWeek([...todoList, ...this.data.completedList])
          const todoWeeklyTodos = this.groupTodosByWeek(todoList)
          
          this.setData({
            todoList: todoList,
            weeklyTodos: weeklyTodos,
            todoWeeklyTodos: todoWeeklyTodos
          })
          
          // 保存到本地存储
          wx.setStorageSync('todoList', todoList)
          
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
  },

  // 删除已完成事项
  deleteCompleted: function(e) {
    const id = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个已完成事项吗？',
      success: res => {
        if (res.confirm) {
          const completedList = this.data.completedList.filter(todo => todo.id !== id)
          
          // 更新时间线数据
          const weeklyTodos = this.groupTodosByWeek([...this.data.todoList, ...completedList])
          
          this.setData({
            completedList: completedList,
            weeklyTodos: weeklyTodos
          })
          
          // 保存到本地存储
          wx.setStorageSync('completedList', completedList)
          
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
  },

  // 删除时间线待办事项
  deleteWeeklyTodo: function(e) {
    const { id, weekid } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个待办事项吗？',
      success: res => {
        if (res.confirm) {
          let todoList = this.data.todoList.filter(todo => todo.id !== id)
          let completedList = this.data.completedList.filter(todo => todo.id !== id)
          
          // 更新时间线数据
          const weeklyTodos = this.groupTodosByWeek([...todoList, ...completedList])
          const todoWeeklyTodos = this.groupTodosByWeek(todoList)
          
          this.setData({
            todoList: todoList,
            completedList: completedList,
            weeklyTodos: weeklyTodos,
            todoWeeklyTodos: todoWeeklyTodos
          })
          
          // 保存到本地存储
          wx.setStorageSync('todoList', todoList)
          wx.setStorageSync('completedList', completedList)
          
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
  },

  // 清空已完成事项
  clearCompleted: function() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有已完成事项吗？',
      success: res => {
        if (res.confirm) {
          this.setData({
            completedList: []
          })
          // 保存到本地存储
          wx.setStorageSync('completedList', [])
          wx.showToast({
            title: '清空成功',
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
  }
})